//
//  FastFetch+NSManagedObjectController.m
//  iMAL
//
//  Created by Stefano Pigozzi on 1/31/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "NSManagedObjectContext+FastFetch.h"

@implementation NSManagedObjectContext (FastFetch)

// Convenience method to fetch a single object with a key of a particular 
// numerical value, if the object with given key value doesn't exists then 
// a new one is created and returned for you.
//
- (NSManagedObject *) fetchOrCreateAnimeWithId:(int)value
{
	NSSet *a = [self fetchObjectsForEntityName:@"Anime"
				withPredicate: [NSPredicate predicateWithFormat:@"anime_id == %d", value]];
	
	if(a!=nil && [a count] == 0){		
		NSManagedObject* new_anime = [NSEntityDescription
									  insertNewObjectForEntityForName:@"Anime"
									  inManagedObjectContext:self];
		[new_anime setValue:[NSNumber numberWithInt:value] forKey:@"anime_id"];
		return new_anime;
		//[new_anime setValue:@"Cowboy Bebop" forKey:@"title"];
	} else {
		//NSLog(@"fetched: %@", [[[a allObjects] objectAtIndex:0] valueForKey:@"title"]);
		return [[a allObjects] objectAtIndex:0];
	}
	return nil;
}

- (NSManagedObject *) fetchAnimeWithImage:(NSString *) image
{
	NSSet *a = [self fetchObjectsForEntityName:@"Anime"
								 withPredicate: [NSPredicate predicateWithFormat:@"image LIKE %@", image]];
	
	if(a!=nil && [a count] == 0){
	} else {
		//NSLog(@"fetched: %@", [[[a allObjects] objectAtIndex:0] valueForKey:@"title"]);
		return [[a allObjects] objectAtIndex:0];
	}
	return nil;
}

// Convenience method to fetch the array of objects for a given Entity
// name in the context, optionally limiting by a predicate or by a predicate
// made from a format NSString and variable arguments.
//
- (NSSet *)fetchObjectsForEntityName:(NSString *)newEntityName
					   withPredicate:(id)stringOrPredicate, ...
{
    NSEntityDescription *entity = [NSEntityDescription
								   entityForName:newEntityName inManagedObjectContext:self];
	
    NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
    [request setEntity:entity];
    
    if (stringOrPredicate)
    {
        NSPredicate *predicate;
        if ([stringOrPredicate isKindOfClass:[NSString class]])
        {
            va_list variadicArguments;
            va_start(variadicArguments, stringOrPredicate);
            predicate = [NSPredicate predicateWithFormat:stringOrPredicate
											   arguments:variadicArguments];
            va_end(variadicArguments);
        }
        else
        {
            NSAssert2([stringOrPredicate isKindOfClass:[NSPredicate class]],
					  @"Second parameter passed to %s is of unexpected class %@",
					  sel_getName(_cmd), [stringOrPredicate className]);
            predicate = (NSPredicate *)stringOrPredicate;
        }
        [request setPredicate:predicate];
    }
	
    NSError *error = nil;
    NSArray *results = [self executeFetchRequest:request error:&error];
    if (error != nil)
    {
        [NSException raise:NSGenericException format:[error description]];
    }
    
    return [NSSet setWithArray:results];
}
	
@end
